package root.electronclass.electronclass

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import com.blankj.utilcode.util.SPUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import root.electronclass.electronclass.common.base.BaseActivity
import root.electronclass.electronclass.common.base.BaseFragment
import root.electronclass.electronclass.common.base.CommonDialogFragment
import root.electronclass.electronclass.common.event.NetWorkEvent
import root.electronclass.electronclass.common.util.ActivityManager
import root.electronclass.electronclass.databinding.ActivityCommonBinding
import root.electronclass.electronclass.personal.dialog.TipsDialog

/**
 * CommonActivity
 * lokiy
 * 2020-12-14
 */
class CommonActivity : BaseActivity() {
    private var mFragment: Fragment? = null
    val binding by lazy { ActivityCommonBinding.inflate(layoutInflater) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
        @Suppress("UNCHECKED_CAST") val clazz = intent.getSerializableExtra("_FRAGMENT_CLASS") as Class<out Fragment>
        setContentView(binding.root)

        binding.top.setup(lifecycle)
        intent.getStringExtra(TITLE)?.let { binding.top.title(it) }
        val supportFragmentManager = supportFragmentManager
        val tag = clazz.simpleName
        if (supportFragmentManager.findFragmentByTag(tag).also { mFragment = it } == null) {
            supportFragmentManager.beginTransaction()
                .add(R.id.container, Fragment.instantiate(this, clazz.name, intent.extras).also { mFragment = it }, tag)
                .commitNow()
        }
        binding.back.setOnClickListener {
            onBackPressed()
        }
        binding.home.setOnClickListener {
            ActivityManager.getInstance().finishOtherActivity(MainActivity::class.java)
        }
        setWindowBackGround()
    }

    override fun setTitle(title: CharSequence?) {
        super.setTitle(title)
        binding.top.title(title?.toString().orEmpty())
    }
    /**
     * 设置全局背景图片
     */
    private fun setWindowBackGround(){
        val view: View = this.window.decorView
        val src = SPUtils.getInstance().getInt("bg-key", R.mipmap.bg2)
        view.setBackgroundResource(src)
    }

    override fun onBackPressed() {
        supportFragmentManager.fragments.lastOrNull()?.let {
            if (it is BaseFragment && it.onBackPressed()) {
                return
            }
        }
        super.onBackPressed()
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onNetWorkEvent(event: NetWorkEvent) {
        if (!event.connect) {
            TipsDialog().also {
                it.arguments = bundleOf(
                    CommonDialogFragment.TITLE to "温馨提示",
                    CommonDialogFragment.CLOSE to true
                )
            }.show(supportFragmentManager, "TIPS")
        }
    }

    companion object {

        const val TITLE = "_TITLE"

        fun startActivity(context: Context?, clazz: Class<out Fragment?>?, bundle: Bundle? = null) {
            startActivityForResult(context, clazz, bundle, -1)
        }

        fun startActivityForResult(context: Context?, clazz: Class<out Fragment?>?, bundle: Bundle?, requestCode: Int) {
            if (context is Activity) {
                val intent = Intent(context, CommonActivity::class.java)
                if (bundle != null) {
                    intent.putExtras(bundle)
                }
                intent.putExtra("_FRAGMENT_CLASS", clazz)
                if (requestCode != 0 && context is CommonActivity) {
                    val fragments = context.supportFragmentManager.fragments
                    var fragment: Fragment? = null
                    for (i in fragments.indices.reversed()) {
                        val f = fragments[i]
                        if (f is BaseFragment) {
                            fragment = f
                            break
                        }
                    }
                    if (fragment != null) {
                        fragment.startActivityForResult(intent, requestCode)
                    } else {
                        (context as Activity).startActivityForResult(intent, requestCode)
                    }
                } else {
                    context.startActivityForResult(intent, requestCode)
                }
            }
        }

        fun startActivityForResult(fragment: Fragment, clazz: Class<out Fragment?>?, bundle: Bundle?, requestCode: Int) {
            val intent = Intent(fragment.activity, CommonActivity::class.java)
            if (bundle != null) {
                intent.putExtras(bundle)
            }
            intent.putExtra("_FRAGMENT_CLASS", clazz)
            fragment.startActivityForResult(intent, requestCode)
        }
    }
}
